package com.changanw.dd.datasource;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import io.seata.rm.datasource.DataSourceProxy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Component
@EnableConfigurationProperties(DruidProperties.class)
public class LoadDataSource {
    @Autowired
    DruidProperties druidProperties;
    public Map<String, DataSourceProxy> loadAllDatasource(){
        //DataSourceProxy seata 带来的数据源对象，用以解决多数据源下的分布式事务
        Map<String, DataSourceProxy> dataSourceMap = new HashMap<>();
        final Map<String, Map<String, String>> ds = druidProperties.getDs();
        try {
            final Set<String> keySet = ds.keySet();
            for (String s : keySet) {
                DataSource dataSource = druidProperties.dataSource((DruidDataSource) DruidDataSourceFactory.createDataSource(ds.get(s)));
                dataSourceMap.put(s,new DataSourceProxy(dataSource));
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        return dataSourceMap;
    }
}
